package com.example.common.recycler.viewbinding;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewbinding.ViewBinding;

import com.example.common.recycler.base.BaseBindView;
import com.example.common.recycler.base.BindViewStore;
import com.example.common.recycler.base.IBIndViewManager;

import java.util.List;

/**
 * 为了满足一个实体对应多种布局的场景
 * @param <T>
 * @param <VB>
 */
public class ViewBindingBindViewManager2<T, VB extends ViewBinding> implements IBIndViewManager<T, ViewBindingViewHolder<VB>, BaseViewBindingBindView2<T, VB>> {
    private BindViewStore<BaseViewBindingBindView2<T, VB>> bindViewStore = new BindViewStore<>();
    //<viewtype,hashcode>
    private SparseArray<T> bindViewHashCode = new SparseArray<>();

    @Override
    public ViewBindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        T item = bindViewHashCode.get(viewType);
        int hashcode = getHashCode(item);
        BaseViewBindingBindView2 baseViewBindingBindView = bindViewStore.getBindView(hashcode);
        View view = getItemView(parent, viewType);
        return new ViewBindingViewHolder(baseViewBindingBindView.getBinding(view, item));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewBindingViewHolder<VB> holder, int position, @NonNull T t, @NonNull List<Object> payloads) {
        int type = getHashCode(t);
        bindViewStore.getBindView(type).bindViewData(holder, position, t, payloads);
    }

    @Override
    public void onViewRecycled(@NonNull ViewBindingViewHolder<VB> holder, @NonNull T t) {
        int code = getHashCode(t);
        BaseBindView bindView = bindViewStore.getBindView(code);
        if (bindView == null) {
            return;
        }
        bindView.onViewRecycled(holder);
    }

    @Override
    public void register(@NonNull BaseViewBindingBindView2 bindView) {
        bindViewStore.putBindView(bindView.itemBeanType.hashCode(), bindView);
    }

    public View getItemView(@NonNull ViewGroup parent, int viewType) {
        return LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
    }

    @Override
    public int getItemViewType(int position, @NonNull T t) {
        int type = t.getClass().hashCode();
        int resId = bindViewStore.getBindView(type).getItemLayoutResId(t);
        bindViewHashCode.put(resId, t);
        return resId;
    }

    private int getHashCode(@NonNull T t) {
        return t.getClass().hashCode();
    }
}